package com.miaoda.miaoda_ai.service.impl;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.miaoda.miaoda_ai.constant.UserConstant;
import com.miaoda.miaoda_ai.exception.ErrorCode;
import com.miaoda.miaoda_ai.exception.ThrowUtils;
import com.miaoda.miaoda_ai.mapper.UserMapper;
import com.miaoda.miaoda_ai.model.dto.user.UserQueryRequest;
import com.miaoda.miaoda_ai.model.entity.User;
import com.miaoda.miaoda_ai.model.enums.UserRoleEnum;
import com.miaoda.miaoda_ai.model.vo.user.LoginUserVO;
import com.miaoda.miaoda_ai.model.vo.user.UserVO;
import com.mybatisflex.core.query.QueryWrapper;
import com.mybatisflex.spring.service.impl.ServiceImpl;

import com.miaoda.miaoda_ai.service.UserService;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * 用户 服务层实现。
 *
 * @author <a href="https://github.com/luyixun123asdf"> luyixun</a>
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    private static final String SALT = "miaoda_lyx";

    @Override
    public long userRegister(String userAccount, String userPassword, String checkPassword) {
        // 1.参数校验
        if (StrUtil.hasBlank(userAccount, userPassword, checkPassword)) {
            ThrowUtils.throwIf(true, ErrorCode.PARAMS_ERROR);
        }
        if (userAccount.length() < 4 || userPassword.length() < 8 || userPassword.length() > 16) {
            ThrowUtils.throwIf(true, ErrorCode.PARAMS_ERROR, "用户密码长度不能小于8位，大于16位");
        }
        // 2.密码校验
        if (!userPassword.equals(checkPassword)) {
            ThrowUtils.throwIf(true, ErrorCode.PARAMS_ERROR, "两次输入的密码不一致");
        }

        // 3.加密密码
        // 是否已经存在用户
        QueryWrapper eq = new QueryWrapper().eq(User::getUserAccount, userAccount);
        long l = this.mapper.selectCountByQuery(eq);
        ThrowUtils.throwIf(l > 0, ErrorCode.PARAMS_ERROR, "用户已存在");
        String encryptPassword = encryptPassword(userPassword);
        // 4.插入数据库
        User user = new User();
        user.setUserAccount(userAccount);
        user.setUserPassword(encryptPassword);
        user.setUserName(RandomUtil.randomString(4));
        user.setUserRole(UserRoleEnum.USER.getValue());
        boolean save = this.save(user);
        ThrowUtils.throwIf(!save, ErrorCode.SYSTEM_ERROR, "用户注册失败");
        return user.getId();
    }

    /**
     * 获取脱敏后的登录用户信息
     *
     * @param user
     * @return
     */
    @Override
    public LoginUserVO getLoginUserVO(User user) {
        if (user == null) {
            return null;
        }
        LoginUserVO loginUserVO = new LoginUserVO();
        BeanUtils.copyProperties(user, loginUserVO);
        return loginUserVO;
    }

    @Override
    public User getLoginUser(HttpServletRequest request) {
        ThrowUtils.throwIf(request == null, ErrorCode.PARAMS_ERROR);
        User user = (User) request.getSession().getAttribute(UserConstant.USER_LOGIN_STATE);
        ThrowUtils.throwIf(user == null, ErrorCode.NOT_LOGIN_ERROR);
        return user;
    }

    @Override
    public LoginUserVO userLogin(String userAccount, String userPassword, HttpServletRequest request) {
        // 1.参数校验
        if (StrUtil.hasBlank(userAccount, userPassword)) {
            ThrowUtils.throwIf(true, ErrorCode.PARAMS_ERROR, "参数为空");
        }
        if (userAccount.length() < 4 || userPassword.length() < 8 || userPassword.length() > 16) {
            ThrowUtils.throwIf(true, ErrorCode.PARAMS_ERROR, "用户密码长度不能小于8位，大于16位或账户名不正确");
        }
        // 2.密码校验
        String encryptPassword = encryptPassword(userPassword);
        QueryWrapper eq = new QueryWrapper()
                .eq(User::getUserAccount, userAccount)
                .eq(User::getUserPassword, encryptPassword);
        User user = this.mapper.selectOneByQuery(eq);
        // 用户不存在
        ThrowUtils.throwIf(user == null, ErrorCode.PARAMS_ERROR, "用户不存在或密码错误");
        LoginUserVO loginUserVO = getLoginUserVO(user);
        // 3.保存用户信息
        request.getSession().setAttribute(UserConstant.USER_LOGIN_STATE, user);
        return loginUserVO;
    }

    /**
     * 退出登录
     *
     * @param request
     * @return
     */

    @Override
    public boolean userLogout(HttpServletRequest request) {
        Object attribute = request.getSession().getAttribute(UserConstant.USER_LOGIN_STATE);
        if (attribute == null) {
            return true;
        }
        // 移除登录态
        request.getSession().removeAttribute(UserConstant.USER_LOGIN_STATE);
        return true;
    }

    /**
     * 获取脱敏后的用户信息
     *
     * @param user
     * @return
     */

    @Override
    public UserVO getUserVO(User user) {
        if (user == null) {
            return null;
        }
        UserVO userVO = new UserVO();
        BeanUtils.copyProperties(user, userVO);
        return userVO;
    }

    /**
     * 获取脱敏后的用户列表
     *
     * @param userList
     * @return
     */
    @Override
    public List<UserVO> getUserVO(List<User> userList) {
        if (userList == null) {
            return new ArrayList<>();
        }
        return userList.stream().map(this::getUserVO).toList();
    }

    @Override
    public QueryWrapper getQueryWrapper(UserQueryRequest userQueryRequest) {
        ThrowUtils.throwIf(userQueryRequest == null, ErrorCode.PARAMS_ERROR);
        // 创建查询条件
        QueryWrapper queryWrapper = new QueryWrapper();
        // 获取查询条件
        Long id = userQueryRequest.getId();
        String sortField = userQueryRequest.getSortField();
        String sortOrder = userQueryRequest.getSortOrder();
        String userName = userQueryRequest.getUserName();
        String userAccount = userQueryRequest.getUserAccount();
        String userProfile = userQueryRequest.getUserProfile();
        String userRole = userQueryRequest.getUserRole();

        // 拼接查询条件
        return queryWrapper.eq("id", id)
                .eq("userRole", userRole)
                .like("userName", userName)
                .like("userAccount", userAccount)
                .like("userProfile", userProfile)
                .orderBy(sortField, "ascend".equals(sortOrder));
    }

    // 加密密码的方法
    @Override
    public String encryptPassword(String password) {
        return DigestUtils.md5DigestAsHex((SALT + password).getBytes());
    }
}
